package com.paisheng.justlife.utils;

import android.util.Log;

import com.paisheng.justlife.bean.ComBean;
import com.paisheng.justlife.common.SerialNumber;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;

public class SerialPortUtils {


    private final String TAG = "SerialPortUtils";
    private String path = SerialNumber.DEV_TTYS4;
    private Integer baudrate = SerialNumber.IBAUDRATE;
    public boolean serialPortStatus = false; //是否打开串口标志
    public String data;
    public boolean threadStatus; //线程状态，为了安全终止线程
    private ReadThread mReadThread;
    public SerialPort serialPort = null;
    public InputStream inputStream = null;
    public OutputStream outputStream = null;

//
//    private static SerialPortUtils instance;
//
//    private SerialPortUtils() {
//    }
//
//    public static synchronized SerialPortUtils getSerialPortUtils() {
//        if (instance == null) {
//            instance = new SerialPortUtils();
//        }
//        return instance;
//    }


    /**
     * 打开串口
     *
     * @return serialPort串口对象
     */
    public SerialPort openSerialPort() {
        try {
            serialPort = new SerialPort(new File(path), baudrate, 0);
            this.serialPortStatus = true;
            threadStatus = false; //线程状态

            //获取打开的串口中的输入输出流，以便于串口数据的收发
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();

            mReadThread = new ReadThread();
            mReadThread.start(); //开始线程监控是否有数据要接收
        } catch (IOException e) {
            Log.e(TAG, "openSerialPort: 打开串口异常：" + e.toString());
            return serialPort;
        }
        Log.d(TAG, "openSerialPort: 打开串口");

        return serialPort;
    }


    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                try {
                    if (inputStream == null) return;
                    byte[] buffer = new byte[512];
                    int size = inputStream.read(buffer);
                    if (size > 0) {
                        ComBean ComRecData = new ComBean(buffer, size);
                        String sMsg = MyFunc.ByteArrToHex(ComRecData.bRec);
                        if (sMsg.length() == 42 || sMsg.length() == 16 ||sMsg.length() == 18) {
                            System.out.println(sMsg.length() + "长度");
                        } else {
                            Log.e(TAG, sMsg.length() + "长度");
                        }
                        if (sMsg.length() > 18) {
                            onFacilityMessgerListener.onReceive(ComRecData);
                        } else {
                            onDataReceiveListener.onDataReceive(ComRecData);
                        }

                    }
                    try {
                        Thread.sleep(50);//延时50ms
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                    return;
                }

            }


        }
    }


    public void sendSerialPort(String data) {
        byte[] bOutArray = MyFunc.HexToByteArr(data);
        int crc16 = CRCUtils.calcCrc16(bOutArray, bOutArray.length);
        String replace = data + String.format("0x%04x", crc16).replace("0x", "");
        byte[] replaceArray = MyFunc.HexToByteArr(replace);
        try {
            outputStream.write(bOutArray);
            String hex = MyFunc.ByteArrToHex(replaceArray);
            Log.d(TAG, "sendSerialPort: 串口数据发送成功" + hex);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "sendSerialPort: 串口数据发送失败：" + e.toString());
        }
    }


    public OnDataReceiveListener onDataReceiveListener = null;

    public static interface OnDataReceiveListener {
        public void onDataReceive(ComBean ComRecData);
    }


    public void setOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
        onDataReceiveListener = dataReceiveListener;
    }

    public OnFacilityMessgerListener onFacilityMessgerListener;

    public static interface OnFacilityMessgerListener {
        public void onReceive(ComBean ComRecData);
    }

    public void setOnFacilityMessgerListener(OnFacilityMessgerListener onFacility) {
        onFacilityMessgerListener = onFacility;
    }
}
